#include "suffixmodifier.h"
#include <QDir>

SuffixModifier::SuffixModifier(QObject *parent) :
    QObject(parent)
{
}

void SuffixModifier::replace(const QString &strDir, const QString &strOldSuffix, const QString &strNewSuffix)
{
    QDir dir(strDir);
    if (!dir.exists())
    {
        return;
    }
    QFileInfoList fileInfoList = dir.entryInfoList();
    int nProgress = 0;
    for(int i = 0; i < fileInfoList.count(); ++i)
    {
        int nCurProgress = (i + 1) * 100 / fileInfoList.count();
        if ( nProgress  < nCurProgress )
        {
            nProgress = nCurProgress;
            emit processingProgress( nProgress );
        }

        QFileInfo fileInfo = fileInfoList.at(i);
        if( fileInfo.fileName() == "."
                ||fileInfo.fileName() == "..")
        {
            continue;
        }
        if(fileInfo.isDir())
        {
            replace(fileInfo.filePath(), strOldSuffix, strNewSuffix);
        }
        else if(fileInfo.isFile())
        {
            QString strOldFilePath = fileInfo.filePath();
            if (strOldFilePath.endsWith(strOldSuffix))
            {
                QString strNewFilePath = strOldFilePath.left(strOldFilePath.lastIndexOf(".") + 1);
                strNewFilePath.append(strNewSuffix);
                QFile file(fileInfo.filePath());
                file.rename(strNewFilePath);
            }
        }
    }
}
